/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by ，applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { computed, defineComponent, SetupContext, ref, withModifiers, watch, onBeforeUnmount, onMounted, onBeforeMount } from 'vue';
import { PropertyPanelProps, propertyPanelProps } from './composition/props/property-panel.props';
import FPropertyPanelItemList from '../src/component/property-panel-item-list.component';
import { PropertyChangeObject } from './composition/entity/property-entity';
import { propertyDataTemp, propertyConfigTemp } from './mock';

import './composition/class/property-panel.css';

export default defineComponent({
    name: 'FPropertyPanel',
    props: propertyPanelProps,
    emits: [] as (string[] & ThisType<void>) | undefined,
    setup(props: PropertyPanelProps, context: SetupContext) {
        const width = ref(props.width);
        const height = ref(props.height);
        const isWidePanel = ref(props.isWidePanel);
        /** 是否启用搜索 */
        const enableSearch = ref(props.enableSearch);
        /** 使用模式 */
        const mode = ref(props.mode);
        /** 是否持有面板的隐藏显示状态 */
        const isPersitOpenState = ref(props.isPersitOpenState);
        /** isPersitOpenState=true时，控制面板是否隐藏显示 */
        const isShowPanel = ref(props.isShowPanel);
        /** 属性类型 */
        // ref(props.propertyConfig) ||  
        const propertyConfig = ref(propertyConfigTemp);
        /** 属性值 */
        const propertyData = ref(propertyDataTemp);
        /** 是否展示关闭按钮 */
        const showCloseBtn = ref(props.showCloseBtn);
        /** 当前选中的标签页id */
        const selectedTabId = ref(props.selectedTabId);
        /** 当前显示状态 */
        const isOpen = ref(true);
        /** 是否是白色主题 */
        const isWhiteTheme = ref(props.isWhiteTheme);
        /** 外层分类，以标签页形式展示 */
        let categoryTabs: any = [];
        const keyword = ref('');

        const fPropertyPanel = ref<HTMLDivElement>();
        const propertyPanel = ref<HTMLDivElement>();

        const matchedElementRefs: Array<HTMLElement> = [];
        const properties: Array<{
            propertyID: string;
            propertyName: string;
            visible?: boolean;
            categoryId: string;
            category?: any;
            propertyType?: string;
        }> = [];

        /** 当前选中的标签页 */
        let selectedTab: any;

        function onValueChangeEvent(event?: any, searchKey?: string) {
            if (matchedElementRefs && matchedElementRefs.length > 0) {
                matchedElementRefs.forEach((element: HTMLElement) => {
                    // renderer.removeStyle(element, 'color');
                    // element = null;
                });
                // matchedElementRefs.value = [];
            }
            // if (!(elementRef && elementRef.nativeElement)) {
            //     return;
            // }
            // const keyword = searchKey || keyword;
            // const panelElement = elementRef.nativeElement.querySelector(".panel-body");
            if (!keyword.value) {
                //   if (elementRef) {
                //     if (panelElement) {
                //       panelElement.scrollTop = 0;
                //     }
                //   }
            } else {
                //   collectProperties();
                // if (properties && properties.length > 0) {
                // const items = properties.filter((item) => {
                //     if (!item.visible) {
                //         return false;
                //     }
                //     if (item.propertyID && item.propertyID.startsWith(keyword)) {
                //         return true;
                //     }
                //     if (item.propertyName && (item.propertyName.startsWith(keyword) || item.propertyName.includes(keyword))) {
                //         return true;
                //     }
                //     return false;
                // });
                // if (items && items.length > 0) {
                // if (items[0].category.status === 'closed') {
                //     items[0].category.status = 'open';
                // }
                //   setTimeout(() => {
                //     items.forEach((item, index: number) => {
                //       let selector = ''
                //       if (item.propertyType === 'cascade') {
                //         selector = `[categoryId="${item.categoryId}"] [propertyId="${item.propertyID}"] div.col-form-label`
                //       } else {
                //             selector = `[categoryId="${item.categoryId}"]
                // [propertyId="${item.propertyID}"] .property-item label.col-form-label`
                //           }
                //           // const selector = `[categoryId="${item.categoryId}"]
                // [propertyId="${item.propertyID}"] ${item.propertyType === 'cascade' ? '' : '.property-item label.col-form-label'}`;
                //           const element = querySelector(selector);
                //           if (element) {
                //             if (index === 0) {
                //               const panelBodyTop = getElementTop(panelElement);
                //               const elementTop = getElementTop(element);
                //               const offsetTop = elementTop - panelBodyTop - 5;
                //               panelElement.scroll({
                //                 top: offsetTop,
                //                 behavior: 'smooth'
                //               });
                //             }
                //             setElementStyle(element, { color: '#5B89FE' })
                //             matchedElementRefs.push(element);
                //           }
                //         });
                //       }, 50);
                // }
                // }
            }
        }
        /**
         * 抛出属性变更事件
         */
        function _valueChanged(changeObject: PropertyChangeObject) {
            context.emit('propertyChanged', changeObject);
        }
        function _submitModal($event: PropertyChangeObject) {
            context.emit('submitModal', $event);
        }
        function search(searchKey?: string) {
            onValueChangeEvent(null, searchKey);
        }
        /**
         * 回车搜索事件
         * @param event
         */
        function onSearchBoxKeyUpEvent(event: KeyboardEvent) {
            if (event.key === 'Enter') {
                search();
            }
        }
        function onSearchEvent(event: any) {
            search();
        }

        /**
         *  隐藏面板
         */
        function collapse() {
            // isPersitOpenState=true时,由外部确定状态
            if (!isPersitOpenState.value) {
                isOpen.value = false;
            }
            context.emit('closePropertyPanel');
        }
        function onChangeSelectedTab(tab: any) {
            selectedTab = tab;
            selectedTabId.value = selectedTab.tabId;
            // selectedTabChanged.next(tab.tabId);
            keyword.value = '';
        }
        function onClearEvent(event: any) {
            keyword.value = '';
            onValueChangeEvent();
        }
        /** 收折 */
        function changeStatus(item: any) {
            if (!item.status || item.status === 'open') {
                item.status = 'closed';
            } else {
                item.status = 'open';
            }
        }
        /**
         * 将属性分类按照标签页进行归类
         */
        function checkShowTabCategory() {
            categoryTabs = [];
            if (!propertyConfig.value || propertyConfig.value.length === 0) {
                categoryTabs = [
                    {
                        tabId: 'default',
                        tabName: '属性',
                        categoryList: []
                    }
                ];
                selectedTab = null;
                return;
            }
            propertyConfig.value.forEach((config: any) => {
                if (config.tabId) {
                    const propTab = categoryTabs.find((t: any) => t.tabId === config.tabId) as any;
                    if (!propTab) {
                        categoryTabs.push({
                            tabId: config.tabId,
                            tabName: config.tabName,
                            categoryList: [config],
                            hide: config.hide || config.properties.length === 0
                        });
                    } else {
                        propTab.categoryList.push(config);
                        if (propTab.hide) {
                            propTab.hide = config.hide || config.properties.length === 0;
                        }
                    }
                } else {
                    const defaultTab = categoryTabs.find((t: any) => t.tabId === 'default') as any;
                    if (!defaultTab) {
                        categoryTabs.push({
                            tabId: 'default',
                            tabName: '属性',
                            categoryList: [config]
                        });
                    } else {
                        defaultTab.categoryList.push(config);
                    }
                }
            });

            // 记录已选的页签
            if (selectedTabId.value) {
                let selectedTab = categoryTabs.find((tab: any) => tab.tabId === selectedTabId.value && !tab.hide);
                selectedTab = selectedTab || categoryTabs[0];
            } else {
                selectedTab = categoryTabs[0];
            }
            selectedTabId.value = selectedTab.tabId;
        }
        function onSwitcherClickEvent() {
            mode.value = mode.value === 'panel' ? 'sidebar' : 'panel';
            // let width;
            // 收折时清空搜索框；
            if (mode.value === 'panel') {
                setTimeout(() => {
                    search();
                }, 100);
                width.value = '300px';
                //   originalWidth ||
            } else {
                //   originalWidth = elementRef && elementRef.nativeElement && elementRef.nativeElement.offsetWidth || 300;
                width.value = '0px';
            }
        }
        /** 关闭按钮 */
        function handleShowCloseBtn() {
            if (showCloseBtn.value) {
                return (
                    <div class="title-actions">
                        <div class="monaco-toolbar">
                            <div class="monaco-action-bar animated">
                                <ul class="actions-container" role="toolbar">
                                    <li class="action-item" onClick={collapse}>
                                        <span class="f-icon f-icon-close"></span>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                );
            }
        }
        function refreshPanel() {
            checkShowTabCategory();
            // @ViewChildren(PropertyItemListComponent) itemLists: Array<PropertyItemListComponent>;
            // itemLists.forEach((item: any) => item.refresh());
        }
        /** 搜索框 */
        function hanleSearchComponent() {
            // && selectedTab?.tabId !== 'commands'
            if (enableSearch.value) {
                return (
                    <div class="search">
                        <div class="input-group f-state-editable border-left-0 border-right-0">
                            <input
                                class="form-control f-utils-fill text-left pt-3 pb-3 textbox"
                                // [(ngModel)]="keyword"
                                // (ngModelChange)="onValueChangeEvent($event)"
                                type="text"
                                placeholder="输入属性名称或编号快速定位"
                                autocomplete="off"
                                onKeyup={(event) => onSearchBoxKeyUpEvent(event)}></input>
                            <div class="input-group-append" style="margin-left: 0px;">
                                <span
                                    class="input-group-text input-group-clear"
                                    style={[{ display: keyword.value && keyword.value.length > 0 ? '' : 'none' }]}
                                    onClick={(event) => onClearEvent(event)}>
                                    <i class="f-icon modal_close"></i>
                                </span>
                                <span class="input-group-text input-group-clear" onClick={(event) => onSearchEvent(event)}>
                                    <i class="f-icon f-icon-search"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                );
            }
        }
        /** 属性面板值 */
        function handlePanelBody() {
            if (selectedTab) {
                return (
                    <div class="panel-body" ref={propertyPanel}>
                        <ul class={['property-grid', { 'wide-panel': isWidePanel.value }]}>
                            {selectedTab.categoryList.map((category: any) => {
                                // [attr.categoryId]="category?.categoryId"
                                return (
                                    <li>
                                        {!category.hide && !category.hideTitle && (
                                            <span class="group-label" onClick={() => changeStatus(category)}>
                                                <span
                                                    class={[
                                                        'f-icon  mr-2',
                                                        { 'f-legend-show': category.status === 'closed' },
                                                        {
                                                            'f-legend-collapse': category.status === 'open' || category.status === undefined
                                                        }
                                                    ]}></span>
                                                {category.categoryName}
                                            </span>
                                        )}
                                        <div hidden={category.status === 'closed'}>
                                            <FPropertyPanelItemList
                                                category={category}
                                                propertyData={propertyData.value}
                                                triggerRefreshPanel={refreshPanel}></FPropertyPanelItemList>
                                            {/* (valueChanged)="_valueChanged($event)"(submitModal)="_submitModal($event)" */}
                                        </div>
                                    </li>
                                );
                            })}
                        </ul>
                    </div>
                );
            }
        }
        function handCategoryTabs() {
            return categoryTabs.map((tab: any) => {
                return (
                    <div
                        class={['title-label', { active: selectedTab && selectedTab.tabId === tab.tabId }, { hidden: tab.hide }]}
                        onClick={(tab: any) => onChangeSelectedTab(tab)}>
                        <span>{tab.tabName}</span>
                    </div>
                );
            });
        }
        /** 面板展示样式 */
        function handleDisplayMode() {
            if (mode.value === 'sidebar') {
                return (
                    <div class="side-panel h-100" onClick={onSwitcherClickEvent}>
                        <i class="f-icon f-icon-engineering w-100 icon"></i>
                        <span>属性</span>
                    </div>
                );
            }
        }
        function handlePropertyPanelStyleObject() {
            const propertyPanelStyleObject = {
                display: isOpen.value ? 'block' : 'none',
                width: width.value
            } as Record<string, any>;
            return propertyPanelStyleObject;
        }
        function handleSwitcher() {
            return (
                <div class="switcher">
                    <i
                        class="f-icon f-icon-exhale-discount"
                        style={[{ transform: mode.value === 'sidebar' ? 'none' : 'rotate(180deg)' }]}
                        onClick={onSwitcherClickEvent}></i>
                </div>
            );
        }
        onBeforeMount(() => {
            if (isPersitOpenState.value) {
                isOpen.value = isShowPanel.value;
            }
            checkShowTabCategory();
        });
        return () => {
            return (
                <>
                    <div
                        ref={fPropertyPanel}
                        class={['property-panel', { 'white-theme': isWhiteTheme.value }]}
                        style={handlePropertyPanelStyleObject()}>
                        <div class={['propertyPanel panel flex-column', { hidden: mode.value !== 'panel' }]}>
                            <div class={['title d-flex', { 'p-right': showCloseBtn.value }, { only: categoryTabs.length === 1 }]}>
                                {handCategoryTabs()}
                                {handleShowCloseBtn()}
                            </div>
                            {hanleSearchComponent()}
                            {handlePanelBody()}
                        </div>
                        {handleSwitcher()}
                        {handleDisplayMode()}
                    </div>
                </>
            );
        };
    }
});
